import requests

class Interface:

    def __init__(self, config):
        self.config = config
        self.openid_list = []

    def getAccessToken(self):
        try:
            r = requests.get('https://api.weixin.qq.com/cgi-bin/token', params={
                "grant_type": "client_credential",
                "appid": self.config['wx-id'],
                "secret": self.config['wx-secret']
            })
            r = r.json()
            access_token = r['access_token']
            result = access_token
        except:
            result = None
        return result

    def getUserOpenId(self, code):
        try:
            r = requests.get('https://api.weixin.qq.com/sns/jscode2session', params={
                "grant_type": "authorization_code",
                "appid": self.config['wx-id'],
                "secret": self.config['wx-secret'],
                "js_code": code
            })
            r = r.json()
            openid = r['openid']
            if openid not in self.openid_list:
                self.openid_list.append(openid)
            result = {
                "msg": "获取成功！",
                "status": 200
            }
        except:
            result = {
                "msg": "微信openid获取错误",
                "status": 204
            }
        return result
